<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>线程池 | 流沙 | subtitle</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="">
    <meta name="description" content="线程是稀缺资源，不能频繁的创建。解耦作用；线程的创建于执行完全分开，方便维护。应当将其放入一个池子中，可以给其他任务进行复用。">
<meta name="keywords" content="关键字">
<meta property="og:type" content="article">
<meta property="og:title" content="线程池">
<meta property="og:url" content="https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/index.html">
<meta property="og:site_name" content="流沙">
<meta property="og:description" content="线程是稀缺资源，不能频繁的创建。解耦作用；线程的创建于执行完全分开，方便维护。应当将其放入一个池子中，可以给其他任务进行复用。">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-11-01T06:32:56.859Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="线程池">
<meta name="twitter:description" content="线程是稀缺资源，不能频繁的创建。解耦作用；线程的创建于执行完全分开，方便维护。应当将其放入一个池子中，可以给其他任务进行复用。">
    
        <link rel="alternate" type="application/atom+xml" title="流沙" href="/hexoblog/atom.xml">
    
    <link rel="shortcut icon" href="/hexoblog/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background:#3F51B5">
      <div class="brand">
        <a href="/hexoblog/" class="avatar waves-effect waves-circle waves-light">
          <img src="/hexoblog/img/avatar.jpeg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">Wang</h5>
          <a href="mailto:919767736@qq.com" title="919767736@qq.com" class="mail">919767736@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/hexoblog/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/hexoblog/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                归档
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/hexoblog/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/hexoblog/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                分类
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="http://www.weibo.com" target="_blank" >
                <i class="icon icon-lg icon-weibo"></i>
                微博
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="http://ftp.wmgblog.pw"  >
                <i class="icon icon-lg icon-link"></i>
                FTP
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">线程池</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
		
		 
		  <a href="/hexoblog/atom.xml" target="_blank" class="header-icon waves-effect waves-circle waves-light rss" id="menuShare">
           <i class="icon icon-lg icon-rss"></i>
        </a>
            
			
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">线程池</h1>
        <h5 class="subtitle">
            
                <time datetime="2018-08-09T10:14:24.000Z" itemprop="datePublished" class="page-time">
  2018-08-09
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#线程池原理"><span class="post-toc-number">1.</span> <span class="post-toc-text">线程池原理</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#线程池配置"><span class="post-toc-number">2.</span> <span class="post-toc-text">线程池配置</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#线程池的隔离"><span class="post-toc-number">3.</span> <span class="post-toc-text">线程池的隔离</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#线程池的停止"><span class="post-toc-number">4.</span> <span class="post-toc-text">线程池的停止</span></a></li></ol>
        </nav>
    </aside>


<article id="post-ThreadPool"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">线程池</h1>
        <div class="post-meta">
            <time class="post-time" title="2018-08-09 18:14:24" datetime="2018-08-09T10:14:24.000Z"  itemprop="datePublished">2018-08-09</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>线程是稀缺资源，不能频繁的创建。<br>解耦作用；线程的创建于执行完全分开，方便维护。<br>应当将其放入一个池子中，可以给其他任务进行复用。</p>
<a id="more"></a>
<hr>
<h2 id="线程池原理"><a href="#线程池原理" class="headerlink" title="线程池原理"></a>线程池原理</h2><p>核心的思想就是把宝贵的资源放到一个池子中；每次使用都从里面获取，用完之后又放回池子供其他人使用</p>
<p>常见的创建线程池方式有以下几种：</p>
<p><code>Executors.newCachedThreadPool()</code>：无限线程池。</p>
<p><code>Executors.newFixedThreadPool(nThreads)</code>：创建固定大小的线程池。</p>
<p><code>Executors.newSingleThreadExecutor()</code>：创建单个线程的线程池。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public static ExecutorService newCachedThreadPool() &#123;</span><br><span class="line">    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,</span><br><span class="line">                                  60L, TimeUnit.SECONDS,</span><br><span class="line">                                  new SynchronousQueue&lt;Runnable&gt;());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public static ExecutorService newSingleThreadExecutor() &#123;</span><br><span class="line">    return new FinalizableDelegatedExecutorService</span><br><span class="line">        (new ThreadPoolExecutor(1, 1,</span><br><span class="line">                                0L, TimeUnit.MILLISECONDS,</span><br><span class="line">                                new LinkedBlockingQueue&lt;Runnable&gt;()));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public static ExecutorService newFixedThreadPool(int nThreads) &#123;</span><br><span class="line">    return new ThreadPoolExecutor(nThreads, nThreads,</span><br><span class="line">                                  0L, TimeUnit.MILLISECONDS,</span><br><span class="line">                                  new LinkedBlockingQueue&lt;Runnable&gt;());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>都是new的<code>ThreadPoolExecutor</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">public ThreadPoolExecutor(int corePoolSize,</span><br><span class="line">                          int maximumPoolSize,</span><br><span class="line">                          long keepAliveTime,</span><br><span class="line">                          TimeUnit unit,</span><br><span class="line">                          BlockingQueue&lt;Runnable&gt; workQueue,</span><br><span class="line">                          ThreadFactory threadFactory,</span><br><span class="line">                          RejectedExecutionHandler handler) &#123;</span><br><span class="line">    if (corePoolSize &lt; 0 ||</span><br><span class="line">        maximumPoolSize &lt;= 0 ||</span><br><span class="line">        maximumPoolSize &lt; corePoolSize ||</span><br><span class="line">        keepAliveTime &lt; 0)</span><br><span class="line">        throw new IllegalArgumentException();</span><br><span class="line">    if (workQueue == null || threadFactory == null || handler == null)</span><br><span class="line">        throw new NullPointerException();</span><br><span class="line">    this.acc = System.getSecurityManager() == null ?</span><br><span class="line">            null :</span><br><span class="line">            AccessController.getContext();</span><br><span class="line">    this.corePoolSize = corePoolSize;</span><br><span class="line">    this.maximumPoolSize = maximumPoolSize;</span><br><span class="line">    this.workQueue = workQueue;</span><br><span class="line">    this.keepAliveTime = unit.toNanos(keepAliveTime);</span><br><span class="line">    this.threadFactory = threadFactory;</span><br><span class="line">    this.handler = handler;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><p><code>corePoolSize</code> 为线程池的基本大小。</p>
</li>
<li><p><code>maximumPoolSize</code><br>为线程池最大线程大小</p>
</li>
<li><p><code>keepAliveTime</code> <code>unit</code> 则是线程空闲后的存活时间。</p>
</li>
<li><p><code>workQueue</code>  用于存放任务的阻塞队列。</p>
</li>
<li><p><code>threadFactory</code></p>
</li>
<li><p><code>handler</code> 当队列和最大线程池都满了之后的饱和策略。</p>
</li>
</ul>
<blockquote>
<p>threadPool.execute(new Job());</p>
</blockquote>
<ol>
<li>获取当前线程池的状态。</li>
<li>当前线程数量小于 coreSize 时创建一个新的线程运行。</li>
<li>如果当前线程处于运行状态，并且写入阻塞队列成功。</li>
<li>双重检查，再次获取线程状态；如果线程状态变了（非运行状态）就需要从阻塞队列移除任务，并尝试判断线程是否全部执行完毕。同时执行拒绝策略。</li>
<li>如果当前线程池为空就新创建一个线程并执行。</li>
<li>如果在第三步的判断为非运行状态，尝试新建线程，如果失败则执行拒绝策略。</li>
</ol>
<h2 id="线程池配置"><a href="#线程池配置" class="headerlink" title="线程池配置"></a>线程池配置</h2><p>通常我们是需要根据这批任务执行的性质来确定的。</p>
<ul>
<li>IO 密集型任务：由于线程并不是一直在运行，所以可以尽可能的多配置线程，比如 CPU 个数 * 2</li>
<li>CPU 密集型任务（大量复杂的运算）应当分配较少的线程，比如 CPU 个数相当的大小</li>
</ul>
<h2 id="线程池的隔离"><a href="#线程池的隔离" class="headerlink" title="线程池的隔离"></a>线程池的隔离</h2><p>如果我们很多业务都依赖于同一个线程池,当其中一个业务因为各种不可控的原因消耗了所有的线程，导致线程池全部占满。</p>
<p>这样其他的业务也就不能正常运转了，这对系统的打击是巨大的。</p>
<p>不同业务不同的线程池</p>
<h2 id="线程池的停止"><a href="#线程池的停止" class="headerlink" title="线程池的停止"></a>线程池的停止</h2><p><code>shutdown()</code> 执行后停止接受新任务，会把队列的任务执行完毕。<br><code>shutdownNow()</code> 也是停止接受新任务，但会中断所有的任务，将线程池状态变为 stop。</p>
<blockquote>
<p>两个方法都会中断线程，用户可自行判断是否需要响应中断。</p>
</blockquote>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2018-11-01T06:32:56.859Z" itemprop="dateUpdated">2018-11-01 14:32:56</time>
</span><br>


        
        作者留言区
        
    </div>
    
    <footer>
        <a href="https://gitwmg.gitee.io/hexoblog">
            <img src="/hexoblog/img/avatar.jpeg" alt="Wang">
            Wang
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            

            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/&title=《线程池》 — 流沙&pic=https://gitwmg.gitee.io/hexoblog/img/avatar.jpeg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/&title=《线程池》 — 流沙&source=线程是稀缺资源，不能频繁的创建。解耦作用；线程的创建于执行完全分开，方便维护。应当将其放入一个池子中，可以给其他任务进行复用。" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《线程池》 — 流沙&url=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/&via=https://gitwmg.gitee.io/hexoblog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/hexoblog/2018/08/14/java基础/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">java基础</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/hexoblog/2018/08/09/Proxy/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">JDK动态代理</h4>
      </a>
    </div>
  
</nav>



    

















</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/hexoblog/img/wechat.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="/hexoblog/img/wechat.jpg" data-alipay="/hexoblog/img/alipay.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="bottom">
        <p><span>Wang &copy; 2017 - 2018</span>
            <span>
                
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/&title=《线程池》 — 流沙&pic=https://gitwmg.gitee.io/hexoblog/img/avatar.jpeg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/&title=《线程池》 — 流沙&source=线程是稀缺资源，不能频繁的创建。解耦作用；线程的创建于执行完全分开，方便维护。应当将其放入一个池子中，可以给其他任务进行复用。" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《线程池》 — 流沙&url=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/&via=https://gitwmg.gitee.io/hexoblog" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://gitwmg.gitee.io/hexoblog/2018/08/09/ThreadPool/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/hexoblog/', SHARE: true, REWARD: true };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
